<template>
	<view class="signname">
		<view class="form">
			<view class="form-content">
				<canvas v-if="pictrueUrl==''" class="form-content__canvas" canvas-id="canvas_sign"
					@touchstart="touchstart" @touchmove="touchmove" @touchend="touchend" disable-scroll="true"></canvas>
				<image v-else :src="pictrueUrl" class="form-content__image"></image>
			</view>
			<view class="form-footer">
				<button class="form-footer__reset" @click="autographClick(1)">清除</button>
				<button class="form-footer__save" @click="autographClick(2)">保存并设置一键签名</button>
			</view>
		</view>
	</view>
</template>

<script>
	import config from '@/common/config.js'
	export default {
		data() {
			return {
				signFlag: false,
				canvasCtx: '', //绘图图像
				points: [], //路径点集合
				hasSign: false,
				isInit: false,
				pictrueUrl: '',
				// 签名类型
				nameType: '',
				mineUserInfo: {},
				params: {}
			}
		},
		onLoad(options) {
			this.params = JSON.parse(options.params)
			this.canvasCtx = uni.createCanvasContext('canvas_sign', this) //创建绘图对象
			//设置画笔样式
			this.canvasCtx.lineWidth = 6
			// 设置线条的端点样式
			this.canvasCtx.lineCap = 'round'
			// 设置线条的交点样式
			this.canvasCtx.lineJoin = 'round'
		},
		methods: {
			
			// 底部按钮点击操作
			autographClick(type) {
				let that = this
				if (type === 1) {
					//清空画布
					this.hasSign = false
					this.pictrueUrl = ''
					uni.getSystemInfo({
						success: function(res) {
							let canvas = uni.createSelectorQuery().select('.form-content__canvas')
							canvas.boundingClientRect().exec(function(data) {
								console.log('canvas', data)
								console.log('canvas wh:' + data[0].width + 'X' + data[0].height)
								let canvasw = Math.ceil(data[0].width)
								let canvash = Math.ceil(data[0].height)
								that.canvasCtx.fillStyle = '#fff'
								that.canvasCtx.fillRect(0, 0, canvasw, canvash)
								that.canvasCtx.draw(true)
							})
						}
					})
				} else{
					if (!this.hasSign) {
						uni.showToast({
							title: '签名不能为空',
							icon: 'none',
							duration: 2000
						})
						return
					}
					uni.getSystemInfo({
						success: function(res) {
							let canvas = uni.createSelectorQuery().select('.form-content__canvas')
							canvas.boundingClientRect().exec(function(data) {
								let canvasw = Math.ceil(data[0].width)
								let canvash = Math.ceil(data[0].height)
								uni.canvasToTempFilePath({
									destWidth: canvasw,
									destHeight: canvash,
									fileType: 'jpg',
									canvasId: 'canvas_sign',
									success: function(res) {
										console.log('图片导出成功：', res)
										let path = res.tempFilePath
										// 保存图片
										if (type === 2) {
											that.uploadPic(path)
										}
									},
									fail: (err) => {
										console.log('图片导出失败：', err)
									}
								})
							})
						}
					})
				} 
			},

			// 图片上传处理
			uploadPic(tempFile) {
				uni.uploadFile({
					url: config.baseUrl + `/base/upload/uploadFile`,
					filePath: tempFile,
					name: 'file',
					formData: {
						type: 34,
						file: tempFile
					},
					header: {
						// #ifdef MP
						"Content-Type": "multipart/form-data",
						// #endif
						"API-User-Token": uni.getStorageSync('userInfo').token
					},
					success: (uploadFileRes) => {
						let res = JSON.parse(uploadFileRes.data);
						console.log('res===>', res)
						this.pictrueUrl = res.data.fileIds[0]

						let param = {
							userSign: res.data.fileIds[0]
						}
						uni.$u.http.post(`/base/mobile/userInfo/setUserSign`, param).then(res => {
							if (res.code == 0) {
								this.params.signImg = param.userSign
								setTimeout(() => {
									uni.$u.http.post(`/train/mobile/exam/handExam`, this.params).then(r => {
										if (r.code == 0) {
											uni.$u.toast('考试完成')
											uni.navigateTo({
												url: `/pages/subPackagesC/exam/blank?trainId=${this.params.trainId}&examPaperId=${this.params.examPaperId}`
											})
										}
									}).catch(err => {})
								}, 500)
							}
						}).catch(err => {})
					}
				});
			},
			touchstart(e) {
				if (!this.isInit) {
					this.isInit = true
					this.autographClick(1);
				}
				let startX = e.changedTouches[0].x
				let startY = e.changedTouches[0].y
				let startPoint = {
					X: startX,
					Y: startY
				}
				this.points.push(startPoint)
				//每次触摸开始，开启新的路径
				this.canvasCtx.beginPath()
			},
			touchmove(e) {
				let moveX = e.changedTouches[0].x
				let moveY = e.changedTouches[0].y
				let movePoint = {
					X: moveX,
					Y: moveY
				}
				this.points.push(movePoint) //存点
				let len = this.points.length
				if (len >= 2) {
					this.draw() //绘制路径
				}
			},
			touchend() {
				this.points = []
				this.canvasCtx.draw(true)
			},
			draw() {
				let point1 = this.points[0]
				let point2 = this.points[1]
				this.points.shift()
				this.canvasCtx.moveTo(point1.X, point1.Y)
				this.canvasCtx.lineTo(point2.X, point2.Y)
				this.canvasCtx.stroke()
				this.canvasCtx.draw(true)
				this.hasSign = true
			},
		}
	}
</script>

<style lang="scss">
	@function tovmin($rpx) {
		@return #{$rpx * 100 / 750}vmin;
	}

	.signname {
		padding: 30rpx;
		width: 100%;
		height: 100%;

		.form {
			display: flex;
			flex-direction: column;
			width: 100vw;
			height: 100vh;

			.form-content {
				width: 92vw;
				height: 80vh;
				border: 1px solid #f2f2f2;

				&__canvas {
					height: 80vh;
					width: 92vw;
					background-color: rgba(235, 235, 235, 1);

				}

				&__image {
					height: 80vh;
					width: 92vw;
					background-color: rgba(235, 235, 235, 1);
				}
			}

			.form-footer {
				width: 92vw;
				display: flex;
				background: #FFFFFF;
				justify-content: flex-end;
				align-items: center;
				padding: 5px;

				button {
					// width: 89px;
					height: 29px;
					border-radius: 6px;
					font-size: 17px;
					font-weight: bold;
					margin: 0 10px;
					display: flex;
					justify-content: center;
					align-items: center;
				}

				button::after {
					border: none;
				}

				&__reset {
					opacity: 1;
					border: 2rpx solid #008AFE;
				}

				&__save {
					color: rgba(255, 255, 255, 1);
					background-color: rgba(14, 50, 97, 1);
				}
			}
		}
	}
</style>
